package com.healthy.controller;

import com.healthy.common.Res;
import com.healthy.entity.Customerprofile;
import com.healthy.entity.User;
import com.healthy.entity.UserLogin;
import com.healthy.entity.UserRegister;
import com.healthy.mapper.UserMapper;
import com.healthy.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/user")
public class UserController {

    @Autowired
    UserService userService;

    @Autowired
    UserMapper userMapper;


    @GetMapping("/list")
    public Res cuUser (User user){
        return new Res(1,"成功",userService.cuUser());
    }

    @PostMapping("/register")
    public Res register(@RequestBody @Validated(UserRegister.class) User user) {
        if (userService.register(user) != null) {
            return new Res(1, "注册成功", user);
        } else {
            return new Res(0, "注册失败");
        }
    }

    @PostMapping("/login")
    public Res login(@RequestBody @Validated(UserLogin.class) User user) {
        User loginUser = userService.login(user);
        if (loginUser != null) {
            return new Res(1, "登录成功", loginUser);
        } else {
            return new Res(0, "登录失败");
        }
    }

    @GetMapping("/mine/info")
    public Res getMyInfo(@RequestHeader("TOKEN") String token) {
        User currentUser = userService.getUserByToken(token);
        currentUser.setPassword(null);
      if(currentUser!=null){
          return new Res(1, "成功", currentUser);
      }else {
          return new Res(0, "失败");
      }
    }

    @DeleteMapping("/delete/{id}")
    // 获取参数的第二种形式：通过url地址传参，常用于针对单个对象的操作，如删除单个对象
    // 对应前端写法为：this.$axios.delete('/api/user/1')，其中1表示删除id为1的用户
    // 后端注解为：@PathVariable("id")，其中 "id" 与Mapping中的 {id} 相匹配，须同名
    public Res cuDelete(@PathVariable("id") int id) throws Exception {
        int res = userService.cuDeleteByid(id);
        if (res > 0) {
            return new Res(1, "删除成功");
        } else {
            return new Res(0, "删除失败");
        }
    }
    @PatchMapping("/Update")
    public Res cuUpdate(@RequestParam int id,String account,String name) throws Exception{
        int res =userService.cuUpdateByid(id,account,name);
        if (res>0){
            return new Res(1, "修改成功");
        } else {
            return new Res(0, "修改失败");
        }
    }
}
